let autoAnswerInterval = null;
let autoRefreshInterval = null;
let networkCheckInterval = null;
let nightModeInterval = null;
let isNightModeActive = false;
let autoRefreshCounter = 0;

// 配置参数
const config = {
    targetUrl: 'https://12367.pointlinkprox.com/',
    intervals: {
        answerInterval: 4000,      // 默认4秒
        refreshInterval: 1800000,  // 默认30分钟
        networkInterval: 1000,     // 默认1秒
        nightCheckInterval: 60000  // 夜间模式检查间隔(1分钟)
    },
    nightMode: {
        startHour: 20,             // 夜间模式开始时间(晚上8点)
        endHour: 6,                // 夜间模式结束时间(早上6点)
        enabled: true              // 是否启用夜间模式
    }
};

// 从存储加载设置
chrome.storage.sync.get(['intervals', 'nightMode'], (result) => {
    if (result.intervals) Object.assign(config.intervals, result.intervals);
    if (result.nightMode) Object.assign(config.nightMode, result.nightMode);
    
    // 初始化夜间模式检查
    checkNightModeStatus();
    nightModeInterval = setInterval(checkNightModeStatus, config.intervals.nightCheckInterval);
});

// 检查是否为目标页面
function isTargetPage(url) {
    return url && url.startsWith(config.targetUrl);
}

// 获取目标页面的标签页ID
function getTargetTabId(callback) {
    chrome.tabs.query({}, (tabs) => {
        for (let tab of tabs) {
            if (isTargetPage(tab.url)) {
                callback(tab.id);
                return;
            }
        }
        callback(null); // 未找到目标页面
    });
}

// 检查是否应该启用夜间模式
function checkNightModeStatus() {
    const now = new Date();
    const currentHour = now.getHours();
    const newStatus = config.nightMode.enabled && 
                     ((currentHour >= config.nightMode.startHour) || 
                      (currentHour < config.nightMode.endHour));
    
    if (newStatus !== isNightModeActive) {
        isNightModeActive = newStatus;
        console.log(`夜间模式已${isNightModeActive ? '启用' : '禁用'}`);
        
        // 注入或移除空格键监听
        getTargetTabId((tabId) => {
            if (tabId) {
                chrome.scripting.executeScript({
                    target: { tabId: tabId },
                    func: updateSpacebarListener,
                    args: [isNightModeActive]
                });
            }
        });
    }
}

// 注入并执行自动接听函数
function executeAutoClick() {
    getTargetTabId((tabId) => {
        if (tabId) {
            chrome.scripting.executeScript({
                target: { tabId: tabId },
                func: () => {
                    const connected_button = document.querySelector("#app > div > div.scmcc-layout-frame.theme-bg-gray-color > div.scmcc-layout-frame-right > div.scmcc-header > div.scmcc-header-center > div.cinccbar > ul > li:nth-child(4) > button");
                    if (connected_button && !connected_button.disabled) {
                        console.log("接听按钮亮起，自动点击");
                        connected_button.click();
                        return true;
                    }
                    console.log("接听按钮未亮起");
                    return false;
                }
            });
        } else {
            console.log("未找到目标页面，跳过自动接听操作");
        }
    });
}

// 注入并执行自动刷新函数
function executeAutoRefresh() {
    getTargetTabId((tabId) => {
        if (tabId) {
            chrome.scripting.executeScript({
                target: { tabId: tabId },
                func: (counter) => {
                    const busy_button = document.querySelector("#app > div > div.scmcc-layout-frame.theme-bg-gray-color > div.scmcc-layout-frame-right > div.scmcc-header > div.scmcc-header-center > div.cinccbar > ul > li:nth-child(2) > button");
                    const free_button = document.querySelector("#app > div > div.scmcc-layout-frame.theme-bg-gray-color > div.scmcc-layout-frame-right > div.scmcc-header > div.scmcc-header-center > div.cinccbar > ul > li:nth-child(3) > button");
                    
                    if (!busy_button || !free_button) {
                        console.log("未找到状态按钮");
                        return { success: false, counter: counter };
                    }
                    
                    // 检测状态
                    if (busy_button.disabled) {
                        console.log("当前状态忙,不执行刷新");
                        return { success: false, counter: counter };
                    }
                    
                    // 执行刷新操作
                    busy_button.click();
                    setTimeout(() => { free_button.click(); }, 1000);
                    counter++;
                    console.log("当前自动刷新共执行了" + counter + "次");
                    return { success: true, counter: counter };
                },
                args: [autoRefreshCounter]
            }, (results) => {
                if (results && results[0] && results[0].result) {
                    autoRefreshCounter = results[0].result.counter;
                }
            });
        } else {
            console.log("未找到目标页面，跳过自动刷新操作");
        }
    });
}

// 注入并执行网络检测函数
function executeNetworkCheck() {
    getTargetTabId((tabId) => {
        if (tabId) {
            chrome.scripting.executeScript({
                target: { tabId: tabId },
                func: () => {
                    const now = new Date();
                    let isOnline = navigator.onLine;
                    if (!isOnline) {
                        console.warn(now + "网络异常");
                        alert(now + "网络异常，请及时处理。");
                        return false;
                    }
                    return true;
                }
            });
        } else {
            console.log("未找到目标页面，跳过网络检测");
        }
    });
}

// 更新空格键监听函数(将被注入到页面)
function updateSpacebarListener(enable) {
    // 移除已存在的监听
    if (window.spacebarAnswerListener) {
        document.removeEventListener('keydown', window.spacebarAnswerListener);
        window.spacebarAnswerListener = null;
    }
    
    // 如果需要启用，添加新的监听
    if (enable) {
        window.spacebarAnswerListener = function(e) {
            // 检查是否按下空格键
            if (e.code === 'Space') {
                const connected_button = document.querySelector("#app > div > div.scmcc-layout-frame.theme-bg-gray-color > div.scmcc-layout-frame-right > div.scmcc-header > div.scmcc-header-center > div.cinccbar > ul > li:nth-child(4) > button");
                if (connected_button && !connected_button.disabled) {
                    console.log("空格键触发接听");
                    connected_button.click();
                    // 阻止空格键的默认行为(如页面滚动)
                    e.preventDefault();
                    return false;
                }
            }
        };
        document.addEventListener('keydown', window.spacebarAnswerListener);
        console.log("夜间模式空格键接听已启用");
    } else {
        console.log("夜间模式空格键接听已禁用");
    }
}

// 消息监听
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    switch (request.action) {
        case 'getStatus':
            sendResponse({
                autoAnswerRunning: !!autoAnswerInterval,
                autoRefreshRunning: !!autoRefreshInterval,
                networkCheckRunning: !!networkCheckInterval,
                isNightModeActive: isNightModeActive,
                autoRefreshCounter: autoRefreshCounter,
                intervals: config.intervals,
                nightMode: config.nightMode
            });
            break;
            
        case 'startAutoAnswer':
            if (!autoAnswerInterval) {
                const interval = request.interval || config.intervals.answerInterval;
                autoAnswerInterval = setInterval(executeAutoClick, interval);
                sendResponse({ success: true });
            } else {
                sendResponse({ success: false, message: "已经在运行中" });
            }
            break;
            
        case 'stopAutoAnswer':
            if (autoAnswerInterval) {
                clearInterval(autoAnswerInterval);
                autoAnswerInterval = null;
                sendResponse({ success: true });
            } else {
                sendResponse({ success: false, message: "没有在运行中" });
            }
            break;
            
        case 'startAutoRefresh':
            if (!autoRefreshInterval) {
                const interval = request.interval || config.intervals.refreshInterval;
                autoRefreshCounter = 0;
                autoRefreshInterval = setInterval(executeAutoRefresh, interval);
                sendResponse({ success: true });
            } else {
                sendResponse({ success: false, message: "已经在运行中" });
            }
            break;
            
        case 'stopAutoRefresh':
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
                autoRefreshInterval = null;
                sendResponse({ success: true });
            } else {
                sendResponse({ success: false, message: "没有在运行中" });
            }
            break;
            
        case 'startNetworkCheck':
            if (!networkCheckInterval) {
                const interval = request.interval || config.intervals.networkInterval;
                networkCheckInterval = setInterval(executeNetworkCheck, interval);
                sendResponse({ success: true });
            } else {
                sendResponse({ success: false, message: "已经在运行中" });
            }
            break;
            
        case 'stopNetworkCheck':
            if (networkCheckInterval) {
                clearInterval(networkCheckInterval);
                networkCheckInterval = null;
                sendResponse({ success: true });
            } else {
                sendResponse({ success: false, message: "没有在运行中" });
            }
            break;
            
        case 'updateIntervals':
            if (request.intervals) {
                Object.assign(config.intervals, request.intervals);
                
                // 更新正在运行的定时器
                if (autoAnswerInterval && request.intervals.answerInterval) {
                    clearInterval(autoAnswerInterval);
                    autoAnswerInterval = setInterval(executeAutoClick, config.intervals.answerInterval);
                }
                
                if (autoRefreshInterval && request.intervals.refreshInterval) {
                    clearInterval(autoRefreshInterval);
                    autoRefreshInterval = setInterval(executeAutoRefresh, config.intervals.refreshInterval);
                }
                
                if (networkCheckInterval && request.intervals.networkInterval) {
                    clearInterval(networkCheckInterval);
                    networkCheckInterval = setInterval(executeNetworkCheck, config.intervals.networkInterval);
                }
                
                chrome.storage.sync.set({ intervals: config.intervals });
            }
            sendResponse({ success: true });
            break;
            
        case 'updateNightMode':
            if (request.nightMode) {
                Object.assign(config.nightMode, request.nightMode);
                chrome.storage.sync.set({ nightMode: config.nightMode });
                // 立即检查夜间模式状态
                checkNightModeStatus();
            }
            sendResponse({ success: true });
            break;
            
        default:
            sendResponse({ success: false, message: "未知命令" });
    }
});

// 监听页面关闭，清理定时器
chrome.tabs.onRemoved.addListener(() => {
    // 不清理定时器，实现切换页面不停止
    console.log("页面已关闭，但保持后台任务运行");
});
    